package com.musemun.service.function.functionimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.musemun.exception.MyDefineException;
import com.musemun.mapper.RoleMapper;
import com.musemun.pojo.Employee;
import com.musemun.pojo.Role;
import com.musemun.service.EmployeeService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *     springSecurity的UserDetailService登入重写
 * </p>
 * @author winner
 * @date 2020/5/8
 */
@Service
public class EmployeeDetailService implements UserDetailsService {
    @Resource
    private EmployeeService employeeService;
    @Resource
    private RoleMapper roleMapper;
    @Override
    public Employee loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StringUtils.isEmpty(username)){
            throw new UsernameNotFoundException("用户名不存在");
        }
        //username=eName+eNo
        Employee employee = employeeService.getOne(new QueryWrapper<Employee>().eq("eName", username));
        if(employee!=null){
            List<Role> roles=roleMapper.getAllRolesByEno(employee.getENo());
            employee.setAuthorities(roles);
        }
        return employee;
    }
}
//    Employee employee = employeeService.getOne(new QueryWrapper<Employee>().eq("eName", username));
//    List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(employee.getRoles());
//        employee.setAuthorities(grantedAuthorities);
//                return employee;